package com.egoo.ticket.server.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.egoo.ticket.server.config.redis.RedisKeyConstant;
import com.egoo.ticket.server.dao.EwsUserDao;
import com.egoo.ticket.server.dao.WorkOrderDao;
import com.egoo.ticket.server.dao.WorkOrderFieldReflectDao;
import com.egoo.ticket.server.dao.WorkOrderTypeDao;
import com.egoo.ticket.server.pojo.dto.*;
import com.egoo.ticket.server.pojo.entity.EwsUser;
import com.egoo.ticket.server.pojo.entity.WorkOrder;
import com.egoo.ticket.server.pojo.entity.WorkOrderFieldReflect;
import com.egoo.ticket.server.pojo.vo.InteractiveDataVo;
import com.egoo.ticket.server.pojo.vo.WorkOrderTypeVo;
import com.egoo.ticket.server.service.WorkOrderService;
import com.egoo.ticket.server.service.WorkOrderTypeService;
import com.egoo.ticket.server.utils.common.ConstantCode;
import com.egoo.ticket.server.utils.common.DbResponse;
import com.egoo.ticket.server.utils.common.RedisUtil;
import com.egoo.ticket.server.utils.common.ResponseConstant;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.sql.Timestamp;
import java.util.*;


/**
 * 工单的接口
 * @author Donny_dong
 */
@Slf4j
@RestController
@RequestMapping(value = "/v1/WorkOrder", produces = "application/json")
@Api(value = "工单管理",tags = "工单管理",description = "工单管理")
public class WorkOrderController {

	@Autowired
	private WorkOrderService workOrderService;
	@Autowired
	private EwsUserDao ewsUserDao;
	@Autowired
	private WorkOrderFieldReflectDao workOrderFieldReflectDao;
	@Autowired
	private WorkOrderDao workOrderDao;
	@Autowired
	private WorkOrderTypeService workOrderTypeService;
	@Autowired
	private WorkOrderTypeDao workOrderTypeDao;

	@Value("${server.flow-into}")
	private String requestUrl;

	@Autowired
	private RedisUtil redisUtil;


	@ApiOperation(value = "根据工单id获取工单信息", notes = "根据工单id获取工单信息")
	@RequestMapping(method = RequestMethod.GET, value = "/selectById")
	public DbResponse selectById(@ApiParam(value = "id", required = true) @RequestParam("id") String id) {
		DbResponse dbResponse = new DbResponse();
		WorkOrder workOrder = workOrderService.selectById(id);
		dbResponse.setRetCode(200);
		dbResponse.setData(workOrder);
		return dbResponse;
	}

	@ApiOperation(value = "获取工单列表", notes = "获取工单列表")
	@RequestMapping(method = RequestMethod.POST, value = "/select")
	public DbResponse select(@RequestBody WorkOrderSelectInputDto workOrderSelectInputDto,
							 HttpServletRequest request) {
		if (workOrderSelectInputDto.getPageSize() == null) {
			return DbResponse.getDbResponse(ResponseConstant.RES_FAIL_CODE, "分页参数不能为空！", null);
		}
		if (workOrderSelectInputDto.getCurrentPage() == null) {
			return DbResponse.getDbResponse(ResponseConstant.RES_FAIL_CODE, "分页参数不能为空！", null);
		}
		if (StringUtils.isEmpty(workOrderSelectInputDto.getUserId())) {
			return DbResponse.getDbResponse(ResponseConstant.RES_FAIL_CODE, "用户id不能为空！", null);
		}
		String tenantId = request.getHeader(ConstantCode.CurrentUserInfo.TENANT_ID);
		workOrderSelectInputDto.setTenantId(tenantId);
		log.info("header传来的租户id为："+tenantId);
		try {
			DbResponse response = workOrderService.select(workOrderSelectInputDto);
			return response;

		}catch (Exception e){
			log.info("获取工单列表异常："+e);
			return new DbResponse(ResponseConstant.RES_FAIL_CODE, "获取工单列表异常："+e);
		}

	}

	/**
	 * TODO 获取工单列表(交互列表)
	 * @author: victor_tang
	 * @createtime: 2020/5/15 9:54
	 * @param workOrderSelectInputDto 1
	 * @param request 2
	 * @return: com.egoo.ticket.server.utils.common.DbResponse
	 */
	@ApiOperation(value = "获取工单列表(交互列表)", notes = "获取工单列表（交互列表）")
	@RequestMapping(method = RequestMethod.POST, value = "/getWorkOrderList")
	public DbResponse getWorkOrderList(@RequestBody @Valid WorkOrderSelectInputDto workOrderSelectInputDto,
									   HttpServletRequest request) {
		String userId = request.getHeader(ConstantCode.CurrentUserInfo.USER_ID);
		String tenantId = request.getHeader(ConstantCode.CurrentUserInfo.TENANT_ID);
		workOrderSelectInputDto.setTenantId(tenantId);
		workOrderSelectInputDto.setUserId(userId);
		try {
			DbResponse response = paramCheck(workOrderSelectInputDto);
			if (response != null) {
				return response;
			}
			return workOrderService.getWorkOrderList(workOrderSelectInputDto);
		} catch (Exception e) {
			log.info("工单列表查询失败信息为：" + e);
			return DbResponse.getDbResponse(ResponseConstant.RES_FAIL_CODE, ResponseConstant.SELECT_FAIL_MSG, null);
		}
	}

	/**
	 * 参数校验
	 *
	 * @param workOrderSelectInputDto 1
	 * @author: victor_tang
	 * @createtime: 2019/9/20 17:10
	 * @return: com.egoo.ticket.server.utils.DBResponse
	 */
	private DbResponse paramCheck(WorkOrderSelectInputDto workOrderSelectInputDto) {
		if (StringUtils.isEmpty(workOrderSelectInputDto.getUserId())) {
			return DbResponse.getDbResponse(ResponseConstant.RES_FAIL_CODE,
					"用户id不能为空！");
		}
		if (StringUtils.isEmpty(workOrderSelectInputDto.getTenantId())) {
			return DbResponse.getDbResponse(ResponseConstant.RES_FAIL_CODE,
					"租户id不能为空！");
		}
		if (workOrderSelectInputDto.getPageSize() == null) {
			return DbResponse.getDbResponse(ResponseConstant.RES_FAIL_CODE, "分页参数不能为空！");
		}
		if (workOrderSelectInputDto.getCurrentPage() == null) {
			return DbResponse.getDbResponse(ResponseConstant.RES_FAIL_CODE, "分页参数不能为空！");
		}
		return null;
	}

	@ApiOperation(value = "获取所有的工单类型名称", notes = "获取所有的工单类型名称")
	@RequestMapping(method = RequestMethod.GET, value = "/selectAllWorkOrderTypeName")
	public DbResponse selectAllWorkOrderTypeName(HttpServletRequest request) {
		String tenantId = request.getHeader(ConstantCode.CurrentUserInfo.TENANT_ID);
		DbResponse dbResponse = new DbResponse();
		List<InteractiveDataVo> interactiveDataList = workOrderService.selectAllOpenWorkOrderTypeName(tenantId);
		dbResponse.setRetCode(200);
		dbResponse.setData(interactiveDataList);
		return dbResponse;
	}

	@ApiOperation(value = "获取所有的工单状态名称", notes = "获取所有的工单状态名称")
	@RequestMapping(method = RequestMethod.GET, value = "/selectAllWorkOrderStatusName")
	public DbResponse selectAllWorkOrderStatusName(HttpServletRequest request) {
		String tenantId = request.getHeader(ConstantCode.CurrentUserInfo.TENANT_ID);
		DbResponse dbResponse = new DbResponse();
		List<InteractiveDataVo> interactiveDataList = workOrderService.selectAllWorkOrderStatusName(tenantId);
		dbResponse.setRetCode(200);
		dbResponse.setData(interactiveDataList);
		return dbResponse;
	}

	@ApiOperation(value = "批量删除工单", notes = "批量删除工单")
	@RequestMapping(method = RequestMethod.POST, value = "/deleteBatch")
	public DbResponse deleteBatch(@RequestBody WorkOrderDeleteInputDto workOrderDeleteInputDto) {
		String userId = workOrderDeleteInputDto.getUserId();
		EwsUser ewsUser = ewsUserDao.selectById(userId);
		List<String> idList = workOrderDeleteInputDto.getIdList();
		List<WorkOrder> workOrderList = new ArrayList<>();
		for (String id : idList) {
			// 判断改工单是否存在
			WorkOrder workOrder = workOrderService.selectById(id);
			if (workOrder == null) {
				continue;
			}
			workOrder.setLastUserId(userId);
			workOrder.setLastUserName(ewsUser.getName());
			Timestamp time = new Timestamp(System.currentTimeMillis());
			workOrder.setLastUpdateTime(time);
			workOrder.setDeleteStatus(ConstantCode.DELETED_OLD);
			workOrder.setStatusId(ConstantCode.WorkOrderState.ALREDAY_CLOSE);
			workOrder.setCloseTime(time);
			workOrderList.add(workOrder);
		}
		workOrderService.deleteBatch(workOrderList,userId);
		return new DbResponse(ResponseConstant.RES_SUCCESS_CODE, ResponseConstant.DEL_SUCCESS_MSG);
	}

	@ApiOperation(value = "批量关闭工单", notes = "批量关闭工单")
	@RequestMapping(method = RequestMethod.POST, value = "/closeBatch")
	public DbResponse closeBatch(@RequestBody WorkOrderDeleteInputDto workOrderDeleteInputDto) {
		DbResponse dbResponse = new DbResponse(ResponseConstant.RES_FAIL_CODE, "关闭失败");
		String userId = workOrderDeleteInputDto.getUserId();
		EwsUser ewsUser = ewsUserDao.selectById(userId);
		List<String> idList = workOrderDeleteInputDto.getIdList();
		List<WorkOrder> workOrderList = new ArrayList<>();
		for (String id : idList) {
			// 判断改工单是否存在
			WorkOrder workOrder = workOrderService.selectById(id);
			if (workOrder == null) {
				continue;
			}
			workOrder.setLastUserId(userId);
			workOrder.setLastUserName(ewsUser.getName());
			workOrder.setCloseUserId(userId);
			workOrder.setCloseUserName(ewsUser.getName());
			Timestamp time = new Timestamp(System.currentTimeMillis());
			workOrder.setLastUpdateTime(time);
			workOrder.setCloseTime(time);
			workOrder.setStatusId(ConstantCode.WorkOrderState.ALREDAY_CLOSE);
			workOrderList.add(workOrder);
		}
		Integer retCode = workOrderService.closeBatch(workOrderList,userId);
		if (retCode >= 1) {
			dbResponse.setRetCode(200);
			dbResponse.setMsg("关闭成功");
		}
		return dbResponse;
	}

	@ApiOperation(value = "获取创建节点信息", notes = "获取创建节点信息")
	@RequestMapping(method = RequestMethod.GET, value = "/getCreateNode")
	public DbResponse getCreateNode(
			@ApiParam(value = "workOrderTypeId", required = true) @RequestParam(name = "workOrderTypeId") Long workOrderTypeId,
			@RequestParam(name = "formTemplateId")Integer formTemplateId) {
		DbResponse dbResponse = new DbResponse();
		WorkOrderCreateNodeDto workOrderCreateNodeDto = workOrderService.getCreateNode(workOrderTypeId,formTemplateId);
		dbResponse.setRetCode(200);
		dbResponse.setData(workOrderCreateNodeDto);
		return dbResponse;
	}

	@ApiOperation(value = "新建工单", notes = "新建工单")
	@RequestMapping(method = RequestMethod.POST, value = "/create")
	public DbResponse create(@ApiParam(value = "create", required = true) @RequestBody WorkOrderDto workOrderDto,
							 HttpServletRequest request) {
		log.info("=============================================创建工单开始======================" +
				"======================================================================");
		String tenantId = request.getHeader(ConstantCode.CurrentUserInfo.TENANT_ID);
		workOrderDto.setTenantId(tenantId);
		EwsUser ewsUser = ewsUserDao.selectById(workOrderDto.getUserId());
		if (ewsUser == null) {
			return new DbResponse(ResponseConstant.RES_FAIL_CODE, "当前用户信息未找到！");
		}
		DbResponse dbResponse = workOrderService.create(workOrderDto);
		log.info("=============================================创建工单结束====================" +
				"======================================================================");
		return dbResponse;
	}

	@ApiOperation(value = "获取转派时的所有可选节点", notes = "获取转派时的所有可选节点")
	@RequestMapping(method = RequestMethod.GET, value = "/getSelectableNodes")
	public DbResponse getSelectableNodes(
			@ApiParam(value = "工单类型id", required = true) @RequestParam(name = "workOrderTypeId") Long workOrderTypeId,
			@ApiParam(value = "工单类型节点id", required = true) @RequestParam(name = "nodeId") Long nodeId) {
		if (workOrderTypeId==null || workOrderTypeId == 0) {
			return new DbResponse(ResponseConstant.RES_FAIL_CODE, "工单类型id不能为空！");
		}
		if (nodeId==null || nodeId == 0) {
			return new DbResponse(ResponseConstant.RES_FAIL_CODE, "工单类型节点id不能为空！");
		}
		return new DbResponse(ResponseConstant.RES_SUCCESS_CODE, ResponseConstant.SELECT_SUCCESS_MSG,
				workOrderService.getSelectableNodes(workOrderTypeId,nodeId));
	}

	@ApiOperation(value = "获取关联工单列表", notes = "获取关联工单列表")
	@RequestMapping(method = RequestMethod.POST, value = "/getConcatWorkOrderList")
	public DbResponse getConcatWorkOrderList(
			@ApiParam(value = "关联工单id", required = true) @RequestBody WorkOrderDto workOrderDto) {
		try {
			return workOrderService.selectConcatWorkOrderList(workOrderDto);
		} catch (Exception e) {
			log.info("关联工单列表查询异常信息为：" + e);
			return new DbResponse(ResponseConstant.RES_FAIL_CODE, ResponseConstant.SELECT_FAIL_MSG);
		}
	}

	@ApiOperation(value = "取消关联工单", notes = "取消关联工单")
	@RequestMapping(method = RequestMethod.GET, value = "/cancleConcatWorkOrder")
	public DbResponse cancleConcatWorkOrder(
			@ApiParam(value = "当前工单id", required = true) @RequestParam(name = "currentWorkOrderId") String currentWorkOrderId,
			@ApiParam(value = "关联工单id", required = true) @RequestParam(name = "concatWorkOrderId") String concatWorkOrderId) {
		try {
			return workOrderService.cancleConcatWorkOrder(concatWorkOrderId, currentWorkOrderId);
		} catch (Exception e) {
			log.info("取消关联工单异常信息为：" + e);
			return new DbResponse(ResponseConstant.RES_FAIL_CODE, ResponseConstant.CANCEL_CONCAT_SUCCESS_FAIL);
		}
	}


	@ApiOperation(value = "上传文件", notes = "上传文件")
	@RequestMapping(method = RequestMethod.POST, value = "/special/uploadFile/{tenantId}")
	public JSONObject uploadFile(@RequestBody MultipartFile file, @PathVariable(
			"tenantId")String tenantId) {
		JSONObject jsonObject = new JSONObject();
		if (StringUtils.isEmpty(tenantId)) {
			jsonObject.put("error","租户id不能为空！");
			return jsonObject;
		}
		if(file.isEmpty()){
			jsonObject.put("error","文件不存在！");
			return jsonObject;
		}
		return workOrderService.uploadFile(file,tenantId);
	}

	@ApiOperation(value = "获取工单处理信息", notes = "获取工单处理信息")
	@RequestMapping(method = RequestMethod.GET, value = "/getProcessMessage")
	public DbResponse getProcessMessage(
			@ApiParam(value = "工单id", required = true) @RequestParam(name = "id") String id,
			@ApiParam(value = "用户d", required = true) @RequestParam(name = "userId") String userId,
			HttpServletRequest request) {
		userId = request.getHeader(ConstantCode.CurrentUserInfo.USER_ID);
		DbResponse dbResponse = new DbResponse();
		ProcessMessageOutputDto processMessageOutputDto = workOrderService.getProcessMessage(id, userId);
		dbResponse.setRetCode(200);
		dbResponse.setData(processMessageOutputDto);
		return dbResponse;
	}

	@ApiOperation(value = "处理工单", notes = "处理工单")
	@RequestMapping(method = RequestMethod.POST, value = "/processWorkOrder")
	public DbResponse processWorkOrder(@RequestBody WorkOrderDto workOrderDto,
									   HttpServletRequest request) {
		log.info("=============================================处理工单开始======================" +
				"======================================================================");
		if (StringUtils.isEmpty(workOrderDto.getWorkOrderId())) {
			return new DbResponse(ResponseConstant.RES_FAIL_CODE, "工单id不能为空！");
		}
		String tenantId = request.getHeader(ConstantCode.CurrentUserInfo.TENANT_ID);
		workOrderDto.setTenantId(tenantId);
		EwsUser ewsUser = ewsUserDao.selectById(workOrderDto.getUserId());
		if (ewsUser == null) {
			return new DbResponse(ResponseConstant.RES_FAIL_CODE, "当前处理人信息未找到！");
		}
		WorkOrder workOrder = workOrderDao.selectById(workOrderDto.getWorkOrderId());
		int index = workOrder.getCurrentHandlerId().indexOf(workOrderDto.getUserId());
		if (index<0) {
			return new DbResponse(ResponseConstant.RES_FAIL_CODE, "该工单已被处理或撤回，请刷新页面！");
		}
		try {
			String lock = redisUtil.getAndSet(RedisKeyConstant.WORK_ORDER_PROCCESS_LOCK_PREFIX + workOrderDto.getWorkOrderId(), ConstantCode.Y);
			if (StringUtils.isNotBlank(lock)) {
				return new DbResponse(ResponseConstant.RES_FAIL_CODE, "该工单已被处理，请刷新页面！");
			}
			DbResponse dbResponse = workOrderService.processWorkOrder(workOrderDto);
			log.info("=============================================处理工单结束======================" +
					"======================================================================");
			return dbResponse;
		} finally {
			// 删除锁
			redisUtil.del(RedisKeyConstant.WORK_ORDER_PROCCESS_LOCK_PREFIX + workOrderDto.getWorkOrderId());
		}
	}
	
	@ApiOperation(value = "工单任务改派", notes = "工单任务改派")
	@RequestMapping(method = RequestMethod.POST, value = "/updateCurrentHandler")
	public DbResponse updateCurrentHandler(
			@ApiParam(value = "workOrder", required = true) @RequestBody WorkOrderDto workOrderDto,
			HttpServletRequest request) {
		String tenantId = request.getHeader(ConstantCode.CurrentUserInfo.TENANT_ID);
		workOrderDto.setTenantId(tenantId);
		if(StringUtils.isEmpty(workOrderDto.getWorkOrderId())){
			return new DbResponse(ResponseConstant.RES_FAIL_CODE,"工单编号workOrderId不能为空");
		}
		if (StringUtils.isEmpty(workOrderDto.getRoleType())) {
			return new DbResponse(ResponseConstant.RES_FAIL_CODE, "身份类型roleType不能为空");
		}
		if (CollectionUtils.isEmpty(workOrderDto.getRoleIdList())){
			return new DbResponse(ResponseConstant.RES_FAIL_CODE,"roleIdList不能为空");
		}
		if (StringUtils.isEmpty(workOrderDto.getWorkOrderStatus())){
			return new DbResponse(ResponseConstant.RES_FAIL_CODE,"工单状态编码workOrderStatus不能为空");
		}
		if(StringUtils.isEmpty(workOrderDto.getUserId())){
			return new DbResponse(ResponseConstant.RES_FAIL_CODE,"当前用户userId不能为空");
		}
		if (StringUtils.isEmpty(workOrderDto.getProcessInstanceId())){
			return new DbResponse(ResponseConstant.RES_FAIL_CODE,"流程实例processInstanceId不能为空");
		}
		try {
			return workOrderService.updateCurrentHandler(workOrderDto);
		} catch (Exception e) {
			return new DbResponse(ResponseConstant.RES_FAIL_CODE,"改派失败"+e);
		}
	
	}


	/**
	 * @Author Donny_Dong
	 * @Description //TODO 外部创建工单
	 * @Date 17:05 2019/12/27
	 * @Param [jsonObject]
	 * @return com.egoo.ticket.server.utils.DBResponse
	 **/
	@ApiOperation(value = "外部创建/转入创建工单",notes = "外部创建/转入创建工单")
	@RequestMapping(method = RequestMethod.POST,value = "/externalCreate")
	public DbResponse externalCreate(@RequestBody JSONObject jsonObject){
		log.info("推送创建工单时传入的参数信息："+jsonObject);
		String acceptChain = jsonObject.getString("acceptChain");
		if("10".equals(acceptChain)){
			log.info("受理过的工单，无需重复创建");
			return new DbResponse(ResponseConstant.RES_SUCCESS_CODE,"受理过的工单，无需创建");
		}
		String tenantId = jsonObject.getString("tenantId");
		if (StringUtils.isEmpty(tenantId)){
			return new DbResponse(ResponseConstant.RES_FAIL_CODE,"必传字段tenantId不存在");
		}
		WorkOrderDto workOrderDto = new WorkOrderDto();
		if (!jsonObject.containsKey("workOrderTypeId")){
			return new DbResponse(ResponseConstant.RES_FAIL_CODE,"必传workOrderTypeId字段不存在");
		}
		String workOrderTypeId = jsonObject.getString("workOrderTypeId");
		if (StringUtils.isEmpty(workOrderTypeId)){
			return new DbResponse(ResponseConstant.RES_FAIL_CODE,"workOrderTypeId不能为空");
		}
		WorkOrderTypeVo workOrderTypeVo = workOrderTypeDao.selectById(Long.valueOf(workOrderTypeId));
		if (Objects.isNull(workOrderTypeVo)){
			return new DbResponse(ResponseConstant.RES_FAIL_CODE,"无对应流程，确认后重试");
		}
		if(!jsonObject.containsKey("createrId")&& jsonObject.containsKey("createrName")){
			return new DbResponse(ResponseConstant.RES_FAIL_CODE,"必传createrId,createrName字段不存在");
		}
		String createrId = jsonObject.getString("createrId");
		String createrName = jsonObject.getString("createrName");

		if (StringUtils.isEmpty(createrId)&& StringUtils.isEmpty(createrName)){
			return new DbResponse(ResponseConstant.RES_FAIL_CODE,"createrId和createrName不能为空");
		}
		String externalWorkOrderId =null;
		if(jsonObject.containsKey("externalWorkOrderId")&& !StringUtils.isEmpty(jsonObject.getString("externalWorkOrderId"))){
			externalWorkOrderId = jsonObject.getString("externalWorkOrderId");
		}
		if(jsonObject.containsKey("externalFlowInfo") && jsonObject.getJSONObject("externalFlowInfo")!=null){
			JSONObject externalFlowInfo = jsonObject.getJSONObject("externalFlowInfo");
			workOrderDto.setExternalFlowInfo(externalFlowInfo);
		}
		String nodeId = workOrderTypeService.selectStartNodeId(workOrderTypeId);
		JSONObject customField = new JSONObject();
		List<WorkOrderFieldReflect> workOrderFieldReflects = workOrderFieldReflectDao.selectByWorkOrderTypeId(workOrderTypeId,tenantId,nodeId);
		for (WorkOrderFieldReflect workOrderFieldReflect:
		workOrderFieldReflects) {
			String externalFieldName = workOrderFieldReflect.getExternalFieldName();
			String innerFieldName = workOrderFieldReflect.getInnerFieldName();
			String value = null;

			if (StringUtils.isEmpty(externalFieldName)){
				if (!jsonObject.containsKey(innerFieldName)){
					return new DbResponse(ResponseConstant.RES_FAIL_CODE,"创建工单的字段:"+innerFieldName+"不存在");
				}
//				if (ConstantCode.WorkOrderBaseFieldMeanig.CUSTOM_FIELD_FIELD.equals(innerFieldName)){
//					value = jsonObject.getJSONObject(innerFieldName).toString();
//				}else {
//					value = jsonObject.getString(innerFieldName);
//				}
				customField.put(innerFieldName,jsonObject.getString(innerFieldName));
			}else {
				if (!jsonObject.containsKey(externalFieldName)){
					return new DbResponse(ResponseConstant.RES_FAIL_CODE,"创建工单的字段:"+externalFieldName+"不存在");
				}
//				if (ConstantCode.WorkOrderBaseFieldMeanig.CUSTOM_FIELD_FIELD.equals(externalFieldName)){
//////					value = jsonObject.getJSONObject(externalFieldName).toString();
//////				}else {
//////					value = jsonObject.getString(externalFieldName);
//////				}
				customField.put(innerFieldName,jsonObject.getString(externalFieldName));
			}
//			if
//			(innerFieldName.equals(ConstantCode.WorkOrderBaseFieldMeanig.CLIENT_NAME_FIELD)){
//				workOrderDto.setClientName(value);
//			}else if (innerFieldName.equals(ConstantCode.WorkOrderBaseFieldMeanig.CLIENTTEL_FIELD)){
//				workOrderDto.setPhone(value);
//			}else if
//			(innerFieldName.equals(ConstantCode.WorkOrderBaseFieldMeanig.EXTERNAL_WORK_ORDERID_FIELD)){
//				workOrderDto.setExternalWorkOrderId(externalWorkOrderId);
//			}
//			else if (innerFieldName.equals(ConstantCode.WorkOrderBaseFieldMeanig.PRIORITY_FIELD)){
//				workOrderDto.setPriority(value);
//			}else if (innerFieldName.equals(ConstantCode.WorkOrderBaseFieldMeanig.PROBLEMDESC_FIELD)){
//				workOrderDto.setProblemDesc(value);
//			}
//			else if (innerFieldName.equals(ConstantCode.WorkOrderBaseFieldMeanig.SOURCE_FIELD)){
//				workOrderDto.setSource(value);
//			}else if (innerFieldName.equals(ConstantCode.WorkOrderBaseFieldMeanig.TITLE_FIELD)){
//				workOrderDto.setTitle(value);
//			}
//			else if (innerFieldName.equals(ConstantCode.WorkOrderBaseFieldMeanig.CUSTOM_FIELD_FIELD)){
//				workOrderDto.setCustomField(JSON.parseObject(value));
//			}else if (innerFieldName.equals(ConstantCode.WorkOrderBaseFieldMeanig.MERGE_WORK_ORDER_FIELD)){
//				workOrderDto.setCombineWorkOrderIds(value);
//			}
		}
		workOrderDto.setWorkOrderTypeId(Long.valueOf(workOrderTypeId));
		workOrderDto.setTenantId(tenantId);
		workOrderDto.setUserId(createrId);
		workOrderDto.setExternalWorkOrderId(customField.getString("CHANL_PRI_ID"));
		workOrderDto.setCustomField(customField);
		return workOrderService.externalCreate(jsonObject, workOrderDto,workOrderFieldReflects);
	}


	@ApiOperation(value = "工单领取",notes = "工单领取")
	@RequestMapping(method = RequestMethod.POST,value = "/workOrderRecieve")
	public DbResponse workOrderRecieve(@RequestBody JSONObject jsonObject, HttpServletRequest request){
		String tenantId = request.getHeader(ConstantCode.CurrentUserInfo.TENANT_ID);
		if (!jsonObject.containsKey("workOrderId")&& StringUtils.isEmpty(jsonObject.getString("workOrderId"))){
			return new DbResponse(ResponseConstant.RES_FAIL_CODE,"需求字段workOrderId不存在或为空");
		}
		if(!jsonObject.containsKey("userId") && StringUtils.isEmpty(jsonObject.getString("userId"))){
			return new DbResponse(ResponseConstant.RES_FAIL_CODE,"需求字段userId不存在或为空");
		}
		try {
			// 获取添加锁
			String lock = redisUtil.getAndSet(RedisKeyConstant.WORK_ORDER_RECEIVE_LOCK_PREFIX+jsonObject.getString("workOrderId"), ConstantCode.Y);
			if (StringUtils.isNotBlank(lock)) {
				return new DbResponse(ResponseConstant.RES_FAIL_CODE, "该工单已被领取，请刷新页面！");
			}
			jsonObject.put("tenantId",tenantId);
			return workOrderService.workOrderRecieve(jsonObject);
		} finally {
			// 删除锁
			redisUtil.del(RedisKeyConstant.WORK_ORDER_RECEIVE_LOCK_PREFIX+jsonObject.getString("workOrderId"));
		}

	}

	@ApiOperation(value = "获取父类合并工单信息",notes = "获取父类合并工单信息")
	@RequestMapping(method = RequestMethod.POST,value = "/getCombineWorkOrderInfo")
	public DbResponse getParentCombineWorkOrderInfo(@RequestBody WorkOrderDto workOrderDto) {
		if (StringUtils.isEmpty(workOrderDto.getWorkOrderId())){
			return new DbResponse(ResponseConstant.RES_FAIL_CODE,"id不能为空");
		}
		return 	workOrderService.getCombineWorkOrderInfo(workOrderDto);
	}


	@ApiOperation(value = "关注取消工单",notes = "关注取消工单")
	@RequestMapping(method = RequestMethod.POST,value = "/monitorAndCancelWorkOrder")
	public DbResponse monitorAndCancelWorkOrder(@RequestBody JSONObject jsonObject) {

		if( StringUtils.isEmpty(jsonObject.getString("id"))){
			return new DbResponse(ResponseConstant.RES_FAIL_CODE,"工单id不能为空");
		}
		if (StringUtils.isEmpty(jsonObject.getString("userId"))){
			return new DbResponse(ResponseConstant.RES_FAIL_CODE,"用户id不能为空");
		}
		if (StringUtils.isEmpty(jsonObject.getString("isMonitor"))){
			return new DbResponse(ResponseConstant.RES_FAIL_CODE,"关注标记不能为空");
		}
		try {
			workOrderService.monitorAndCancelWorkOrder(jsonObject);
		} catch (Exception e) {
			log.error("关注工单异常："+e);
			return new DbResponse(ResponseConstant.RES_FAIL_CODE,"操作失败");
		}
		return new DbResponse(ResponseConstant.RES_SUCCESS_CODE,"操作成功");
	}


	@ApiOperation(value = "工单撤回",notes = "工单撤回")
	@RequestMapping(method = RequestMethod.POST,value = "/withdrawWorkOrder")
	public DbResponse withdrawWorkOrder(@RequestBody JSONObject jsonObject) {

		if (StringUtils.isEmpty(jsonObject.getString("id"))) {
			return new DbResponse(ResponseConstant.RES_FAIL_CODE, "工单id不能为空");
		}
		if (StringUtils.isEmpty(jsonObject.getString("userId"))) {
			return new DbResponse(ResponseConstant.RES_FAIL_CODE, "用户id不能为空");
		}
		jsonObject.put("button", ConstantCode.WorkOrderLogType.WITHDRAW_NAME);
		DbResponse dbResponse = workOrderService.withdrawWorkOrder(jsonObject);
		return dbResponse;
	}

	@ApiOperation(value = "修改客户唯一标识",notes = "修改客户唯一标识")
	@RequestMapping(method = RequestMethod.POST,value = "/updateCustomIdentify")
	public DbResponse updateCustomIdentify(@RequestBody JSONObject jsonObject,
										   HttpServletRequest request){

		String tenantId = request.getHeader(ConstantCode.CurrentUserInfo.TENANT_ID);
		JSONArray hisCustomIdentify = jsonObject.getJSONArray("hisCustomIdentify");
		String customIdentify = jsonObject.getString("customIdentify");
		if(StringUtils.isEmpty(tenantId)){
			return new DbResponse(ResponseConstant.RES_FAIL_CODE,"tenantId不能为空！");
		}
		if(CollectionUtils.isEmpty(hisCustomIdentify)){
			return new DbResponse(ResponseConstant.RES_FAIL_CODE,"hisCustomIdentify不能为空！");
		}
		if(StringUtils.isEmpty(customIdentify)){
			return new DbResponse(ResponseConstant.RES_FAIL_CODE,"customIdentify不能为空！");
		}
		jsonObject.put("tenantId",tenantId);
		return workOrderService.updateCustomIdentify(jsonObject);
	}


	@ApiOperation(value = "根据sessionId获取工单信息列表",notes = "根据sessionId获取工单信息列表")
	@RequestMapping(method = RequestMethod.GET,value =
			"/getworkOrderInfoBySessionId")
	public DbResponse getworkOrderInfoBySessionId(@RequestParam String sessionId,HttpServletRequest request) {
		if (StringUtils.isEmpty(sessionId)){
			return new DbResponse(ResponseConstant.RES_FAIL_CODE,"sessionId不能为空！");
		}
		String userId = request.getHeader(ConstantCode.CurrentUserInfo.USER_ID);
		try {
			return workOrderService.getworkOrderInfoBySessionId(sessionId,userId);
		} catch (Exception e) {
			log.error("根据sessionId获取工单信息列表异常："+e);
			return new DbResponse(ResponseConstant.RES_FAIL_CODE,"根据sessionId获取工单信息列表异常"+e);

		}

	}

	@ApiOperation(value="外部转入",notes = "外部转入")
	@RequestMapping(method = RequestMethod.POST,value = "/externalFlowInto")
	public DbResponse externalWorkOrderFlowInto(@RequestBody WorkOrderDto workOrderDto){

		if (StringUtils.isEmpty(workOrderDto.getWorkOrderId())){
			return new DbResponse(ResponseConstant.RES_FAIL_CODE,"workOrderId不能为空");
		}
		WorkOrder workOrder = workOrderDao.selectById(workOrderDto.getWorkOrderId());
		if (Objects.isNull(workOrder)){
			return new DbResponse(ResponseConstant.RES_FAIL_CODE,"该工单不存在,请传入正确的工单编号");
		}
//		if (StringUtils.isEmpty(workOrderDto.getWorkOrderTypeId().toString())){
//			return new DbResponse(ResponseConstant.RES_FAIL_CODE,"workOrderTypeId不能为空");
//		}
//		if(StringUtils.isEmpty(workOrderDto.getCurrentWorkOrderNodeId().toString())){
//			return new DbResponse(ResponseConstant.RES_FAIL_CODE,"currentWorkOrderNodeId不能为空");
//		}
//		if(StringUtils.isEmpty(workOrderDto.getExternalFlowType())){
//			return new DbResponse(ResponseConstant.RES_FAIL_CODE,"externalFlowType不能为空");
//		}
		return workOrderService.externalFlowInto(workOrderDto);


	}

	@ApiOperation(value="配置外部转入接口",notes = "配置外部转入接口")
	@RequestMapping(method = RequestMethod.GET,value = "/externalFlowIntoInterface")
	public DbResponse externalWorkOrderFlowIntoInterface() {
		HashMap<String, Object> map = new HashMap<>(8);
		JSONObject jsonObjectFlowInfo = new JSONObject();
		JSONArray arrayFlowRecode = new JSONArray();
		JSONObject jsonObjectFlowRecode = new JSONObject();
		jsonObjectFlowRecode.put("Performer","对应节点处理人");
		jsonObjectFlowRecode.put("ActionTime","对应处理时间");
		jsonObjectFlowRecode.put("StepName","对应处理环节");
		jsonObjectFlowRecode.put("Action","对应处理意见");
		JSONArray arrayFile = new JSONArray();
		JSONObject jsonObjectFile = new JSONObject();
		jsonObjectFile.put("url","文件上传地址");
		jsonObjectFile.put("name","文件名");
		arrayFile.add(jsonObjectFile);
		jsonObjectFlowRecode.put("fileList",arrayFile);
		arrayFlowRecode.add(jsonObjectFlowRecode);
		jsonObjectFlowInfo.put("externalFlowRecode",arrayFlowRecode);
		jsonObjectFlowInfo.put("externalUserId","外部处理人id");
		jsonObjectFlowInfo.put("externalUserName","外部处理人名");
		JSONObject jsonObjectBody = new JSONObject();
		jsonObjectBody.put(ConstantCode.WorkOrderBaseFieldMeanig.WORK_ORDER_ID_FIELD,ConstantCode.WorkOrderBaseFieldMeanig.WORK_ORDER_ID);
		jsonObjectBody.put("externalFlowInfo",jsonObjectFlowInfo);
		map.put("requestUrl",requestUrl);
		map.put("requestMethod","Post");
		map.put("externalFlowInfo",jsonObjectBody);

		return new DbResponse(ResponseConstant.RES_SUCCESS_CODE,ResponseConstant.SELECT_SUCCESS_MSG,map);
	}

	@ApiOperation(value="配置外部转出接口",notes = "配置外部转出接口")
	@RequestMapping(method = RequestMethod.GET,value = "/externalFlowOutInterface")
	public DbResponse externalWorkOrderFlowOutInterface() {

		JSONObject jsonObject = new JSONObject();
		jsonObject.put(ConstantCode.WorkOrderBaseFieldMeanig.WORK_ORDER_ID_FIELD,ConstantCode.WorkOrderBaseFieldMeanig.WORK_ORDER_ID);
		return new DbResponse(ResponseConstant.RES_SUCCESS_CODE,ResponseConstant.SELECT_SUCCESS_MSG,jsonObject);
	}

	@ApiOperation(value="外部转出",notes = "外部转出")
	@RequestMapping(method = RequestMethod.POST,value = "/externalFlowOut")
	public DbResponse externalWorkOrderFlowOut(@RequestBody WorkOrderDto workOrderDto,
											   HttpServletRequest request){
		String tenantId = request.getHeader(ConstantCode.CurrentUserInfo.TENANT_ID);

		if (StringUtils.isEmpty(workOrderDto.getWorkOrderId())){
			return new DbResponse(ResponseConstant.RES_FAIL_CODE,"workOrderId不能为空");
		}
		if (StringUtils.isEmpty(workOrderDto.getWorkOrderTypeId().toString())){
			return new DbResponse(ResponseConstant.RES_FAIL_CODE,"workOrderTypeId不能为空");
		}
		if(StringUtils.isEmpty(workOrderDto.getCurrentWorkOrderNodeId().toString())){
			return new DbResponse(ResponseConstant.RES_FAIL_CODE,"currentWorkOrderNodeId不能为空");
		}
		workOrderDto.setTenantId(tenantId);
		return workOrderService.processWorkOrder(workOrderDto);
	}
	@ApiOperation(value = "工单驳回上一步",notes = "工单驳回上一步")
	@RequestMapping(method = RequestMethod.POST,value = "/workOrderBackToLastStep")
	public DbResponse workOrderBackToLastStep(@RequestBody JSONObject jsonObject) {

		if (StringUtils.isEmpty(jsonObject.getString("id"))) {
			return new DbResponse(ResponseConstant.RES_FAIL_CODE, "工单id不能为空");
		}
		if (StringUtils.isEmpty(jsonObject.getString("userId"))) {
			return new DbResponse(ResponseConstant.RES_FAIL_CODE, "用户id不能为空");
		}
		jsonObject.put("button", ConstantCode.WorkOrderLogType.OVERRULED_NAME);
		return workOrderService.workOrderBackToLastStep(jsonObject);
	}


	@ApiOperation(value = "获取流程对应的基础字段",notes = "获取流程对应的基础字段")
	@RequestMapping(method = RequestMethod.GET,value = "/allBaseBussinessField")
	public DbResponse allBaseBussinessField(@RequestParam("workOrderTypeId")String workOrderTypeId,HttpServletRequest request) {

		String userId = request.getHeader(ConstantCode.CurrentUserInfo.USER_ID);
		String tenantId = request.getHeader(ConstantCode.CurrentUserInfo.TENANT_ID);
		if (StringUtils.isEmpty(workOrderTypeId)){
			return new DbResponse(ResponseConstant.RES_FAIL_CODE,"类型id不能为空");
		}
		if("0".equals(workOrderTypeId)){
			return new DbResponse(ResponseConstant.RES_SUCCESS_CODE,null);
		}
		return workOrderService.getAllBaseBussinessField(workOrderTypeId,tenantId);
	}

	@ApiOperation(value = "获取高级筛选的数据",notes = "获取高级筛选的数据")
	@RequestMapping(method = RequestMethod.GET,value = "/advancedFilterData")
	public DbResponse advancedFilterData(@RequestParam("workOrderFilterMenuId")String workOrderFilterMenuId,HttpServletRequest request) {

		String userId = request.getHeader(ConstantCode.CurrentUserInfo.USER_ID);
		String tenantId = request.getHeader(ConstantCode.CurrentUserInfo.TENANT_ID);
		if (StringUtils.isEmpty(workOrderFilterMenuId)){
			return new DbResponse(ResponseConstant.RES_FAIL_CODE,"过滤器id不能为空");
		}
		return workOrderService.advancedFilterData(workOrderFilterMenuId,tenantId);

	}

	@ApiOperation(value = "浙能更新工单状态",notes = "浙能更新工单状态")
	@RequestMapping(method = RequestMethod.POST,value = "/updateWorkOderStatus")
	public DbResponse alterWorkOderStatus(@RequestBody JSONObject jsonObject) {

		String chanelPrId = jsonObject.getString("CHANL_PRI_ID");
		String endDate = jsonObject.getString("endDate");
		String stat = jsonObject.getString("stat");

		if (StringUtils.isEmpty(chanelPrId)){
			return new DbResponse(ResponseConstant.RES_FAIL_CODE,"工单id不能为空");
		}
		if (StringUtils.isEmpty(stat)){
			return new DbResponse(ResponseConstant.RES_FAIL_CODE,"状态不能为空");
		}
		int status = Integer.valueOf(stat);
		status = workOrderService.translateStatus(status);
		Map<String, Object> map = new HashMap<>();
		map.put("statusId",status);
		map.put("externalWorkOrderId",chanelPrId);
		map.put("closeTime",endDate);
		return workOrderService.alterWorkOderStatus(map);

	}

}
